"""

Roket Secure Language - Builtin Class (Map)

"""

from Builtins import BuiltinC, BuiltinF
from RSB import Obj

class MapBIC(BuiltinC):
	def __init__(self, type):
		# Call the parent function
		super(MapBIC, self).__init__(type)
		
		# Then associate our functions
		self.constructor = MapBICC("__init__", ["self"])
		self.functions["new"] = NewBIF("new", ["self", "id", "var"]);
		self.functions["has"] = HasBIF("has", ["self","id"]);
		self.functions["delete"] = DeleteBIF("delete", ["self","id"]);
		self.functions["findById"] = FindByIDBIF("findById", ["self","id"]);
		self.functions["findByValue"] = FindByValueBIF("findByValue", ["self","value"]);
	
	def clone(self):
		# This function is used when a new instance of the class is created.
		c = Obj(self.type);
		c.variables = self.variables.copy()
		c.functions = self.functions.copy()
		c.events = self.events.copy()
		if (self.constructor != None):
			c.constructor = self.constructor
		else:
			c.constructor = None
		return c

class MapBICC(BuiltinF):
	def execute(self, engine, args):
		# Set up a new map.
		args[0].map = dict()

class NewBIF(BuiltinF):
	def execute(self, engine, args):
		# Add an element to the map
		if (args[1] in args[0].map):
			self.error(engine, "Can not add new object to map - there is already an object at index \"" + str(args[0]) + "\".")
		
		args[0].map[args[1]] = args[2]
		
		self.BCReturn(float(True), engine)

class HasBIF(BuiltinF):
	def execute(self, engine, args):
		# Returns whether an element is at the specified index.
		self.BCReturn(float(args[1] in args[0].map), engine)

class DeleteBIF(BuiltinF):
	def execute(self, engine, args):
		# Deletes an element at the specified index.
		if (args[1] not in args[0].map):
			self.error(engine, "Can not delete object from map - there is no object at index \"" + str(args[0]) + "\".")
		
		del args[0].map[args[1]];
		self.BCReturn(float(True), engine)

class FindByValueBIF(BuiltinF):
	def execute(self, engine, args):
		# Finds an ID by the value.
		a = args[0].map.items()
		for v in a:
			if (v[1] == args[1]):
				self.BCReturn([float(True), v[0]], engine)
		
		self.BCReturn([float(False), float(0)], engine)

class FindByIDBIF(BuiltinF):
	def execute(self, engine, args):
		# Finds a value by the ID.
		if (args[1] in args[0].map):
			self.BCReturn([float(True), args[0].map[args[1]]], engine)
		else:
			self.BCReturn([float(False), float(0)], engine)
